const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const upload = multer({dest: path.join(__dirname, 'yyy/')});

const app = express();

app.get('/', (req, res, next) => {
  res.send('hello nodejs');
});

// app.options('/upload', cors());

//single('xxx') 对应 上传的 name
app.post('/upload',/* cors(),*/upload.single('file'),(req, res, next) => {
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', '*');
  console.log(req.file);
  let obj = {id: req.file.filename};
  res.send(JSON.stringify(obj));
});
/*app.post('/upload',/!* cors(),*!/upload.array('files',12),(req, res, next) => {
  res.set('Access-Control-Allow-Origin', '*');
  // console.log(req.files);
  res.send(JSON.stringify(req.files.map(file=>file.filename)));
});*/

app.get('/preview/:key', /*cors(),*/(req,res) => {
  // res.set('Access-Control-Allow-Origin', '*');
  console.log(req.params.key);
  res.sendFile(`yyy/${req.params.key}`, {
    root: __dirname
    , headers: {
      'Content-Type': 'image/jpeg'
      ,'Access-Control-Allow-Origin':'*'
      ,'Access-Control-Allow-Methods': '*'
    }
  });
});

app.listen(3000);
